package com.guohong.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.guohong.User;
import com.guohong.dto.OrderDto;
import com.guohong.dto.OrderPageDto;
import com.guohong.entity.Order;
import com.guohong.mapper.OrderMapper;
import com.guohong.service.MaodouUserService;
import com.guohong.service.OrderService;

@Service
public class OrderServiceImpl implements OrderService {
	@Autowired
	private MaodouUserService maodouUserService;

	@Autowired
	private OrderMapper orderMapper;

	@Override
	public List<Order> getOrders() {
		return orderMapper.getOrders();
	}

	@Transactional(readOnly = true)
	@Override
	public OrderPageDto listOrdersByPage(String orderNo, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		Page<Order> orders = orderMapper.listOrdersByPage(orderNo);
		OrderPageDto orderPageDto = null;
		List<OrderDto> orderDtos = null;

		if (!CollectionUtils.isEmpty(orders)) {
			orderPageDto = new OrderPageDto();
			orderDtos = new ArrayList<OrderDto>();

			for (Order order : orders) {
				OrderDto orderDto = new OrderDto();
				BeanUtils.copyProperties(order, orderDto);

				User user = maodouUserService.getUserById(order.getUserId());
				orderDto.setUsername(user.getUsername());
				orderDtos.add(orderDto);
			}

			orderPageDto.setTotal(orders.getTotal());
			orderPageDto.setOrders(orderDtos);
		}

		return orderPageDto;
	}
}
